/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.biz.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.modules.biz.dao.*;
import com.thinkgem.jeesite.modules.biz.entity.*;
import com.thinkgem.jeesite.modules.biz.form.BizPurchaseGetFrom;
import com.thinkgem.jeesite.modules.biz.form.BizPurchaseListFrom;
import com.thinkgem.jeesite.modules.biz.vo.BizPurchaseDetailVo;
import com.thinkgem.jeesite.modules.biz.vo.BizPurchaseVo;
import com.thinkgem.jeesite.modules.biz.vo.BizStockInVo;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.AutoNameUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;

/**
 * 采购单的controllerService
 * @author tiancheng
 * @version 2018-07-13
 */
@Service
@Transactional(readOnly = true)
public class BizPurchaseService extends CrudService<BizPurchaseDao, BizPurchase> {
	@Autowired
	BizPurchaseDao bizPurchaseDao;
	@Autowired
	BizGoodsService bizGoodsService;
	@Autowired
	BizPurchaseDetailService bizPurchaseDetailService;
	@Autowired
	BizPurchaseLogService bizPurchaseLogService;
	@Autowired
	BizStockInDao bizStockInDao;
	@Autowired
	BizStockInDetailDao bizStockInDetailDao;
	@Autowired
	BizPurchaseDetailDao bizPurchaseDetailDao;
	@Autowired
	BizBuyingRequisitionDetailDao bizBuyingRequisitionDetailDao;
	@Autowired
	BizBuyingRequisitionDao bizBuyingRequisitionDao;

	public BizPurchase get(String id) {
		return super.get(id);
	}
	
	public List<BizPurchase> findList(BizPurchase bizPurchase) {
		return super.findList(bizPurchase);
	}
	
	public Page<BizPurchase> findPage(Page<BizPurchase> page, BizPurchase bizPurchase) {
		return super.findPage(page, bizPurchase);
	}

	/**
	 * 财务显示列表
	 * @param page
	 * @param bizPurchase
	 * @return
	 */
	public Page<BizPurchase> findPageForFinance(Page<BizPurchase> page, BizPurchase bizPurchase) {
		if(bizPurchase != null){
			bizPurchase.setStatus("12");
			bizPurchase.setPage(page);
			page.setList(bizPurchaseDao.findListForFinance(bizPurchase));
		}
		return page;
	}


	/**
	 * 手机端访问的采购单的列表
	 * @author tiancheng
	 * @date 2018/8/24 15:21
	 * @param bizPurchaseListFrom
	 * @return
	 */
	public List<BizPurchaseVo> findListApi(BizPurchaseListFrom bizPurchaseListFrom) {
		BizPurchase bizPurchase = new BizPurchase();
		//参数传递  status如果为99查询全部的
		if(!bizPurchaseListFrom.getStatus().equals("99")){
			bizPurchase.setStatus(bizPurchaseListFrom.getStatus());
		}
		bizPurchase.setPageSize(bizPurchaseListFrom.getPageSize());
		bizPurchase.setPageNo((bizPurchaseListFrom.getPageNo()-1)*bizPurchaseListFrom.getPageSize());
		//采购单的集合
		List<BizPurchaseVo> bizPurchaseVos = bizPurchaseDao.findListApi(bizPurchase);
		//查询采购单下的商品的明细
		for (BizPurchaseVo vo:bizPurchaseVos) {
			BizPurchaseDetail dizPurchaseDetail = new BizPurchaseDetail();
			dizPurchaseDetail.setPurchaseId(vo.getPurchaseId());
			//当前采购单下的采购单明细
			List<BizPurchaseDetail> list = bizPurchaseDetailService.findList(dizPurchaseDetail);
			StringBuffer detailGoodsName = new StringBuffer();
			for (BizPurchaseDetail detail:list) {
				detailGoodsName.append(detail.getGoodsName()+",");
			}
			if(detailGoodsName.length() > 0){
				vo.setDetailGoodsName(detailGoodsName.substring(0,detailGoodsName.length()-1)+"共"+list.size()+"类商品。");
			}
		}
		return bizPurchaseVos;
	}


	 /**
	  *	手机端查询采购单的详情
	  * @author tiancheng
	  * @date 2018/8/25 14:43
	  * @param
	  * @return
	  */
	public Map getApi(BizPurchaseGetFrom bizPurchaseGetFrom){
		Map map = new HashMap();
		//采购单的信息
		BizPurchaseVo bizPurchaseVo = bizPurchaseDao.getApi(bizPurchaseGetFrom.getPurchaseId());
		map.put("purchaseId",bizPurchaseVo.getPurchaseId());
		map.put("purchaseCode",bizPurchaseVo.getPurchaseCode());
		map.put("status",bizPurchaseVo.getStatus());
		//查询采购单的明细
		List<BizPurchaseDetailVo> bizPurchaseDetailVoList = bizPurchaseDetailService.findListApi(bizPurchaseGetFrom.getPurchaseId());
		for (BizPurchaseDetailVo bizPurchaseDetailVo:bizPurchaseDetailVoList) {
			if(null != bizPurchaseDetailVo && bizPurchaseDetailVo.getGoodsCode() != null){
				//01 酱料  06 冷链 （以前定的是酱料生成条码，由于没有安卓，所以默认冷链也是酱料）
				String type = bizPurchaseDetailVo.getGoodsCode().substring(0,1);
				if(type.equals("J") || type.equals("L")){
					bizPurchaseDetailVo.setType("01");
				}else{
					bizPurchaseDetailVo.setType(bizPurchaseDetailVo.getGoodsCode().substring(0,2	));
				}

			}
		}
		map.put("bizPurchaseDetailVoList",bizPurchaseDetailVoList);
		//查询是否有入库单
		BizStockIn bizStockIn = new BizStockIn();
		bizStockIn.setPurchaseId(bizPurchaseGetFrom.getPurchaseId());
		List<BizStockInVo> bizStockInVoList = bizStockInDao.findListApi(bizStockIn);
		//查询入库单明细
//		for (BizStockInVo stockInVo:bizStockInVoList) {
//			BizStockInDetail bizStockInDetail = new BizStockInDetail();
//			bizStockInDetail.setStockInId(stockInVo.getStockInId());
//			List<BizStockInDetailVo> bizStockInDetailVoList = bizStockInDetailDao.findListApi(bizStockInDetail);
//			stockInVo.setBizStockInDetailList(bizStockInDetailVoList);
//		}
		map.put("bizStockInVoList",bizStockInVoList);
		return map;
	}

	
	@Transactional(readOnly = false)
	public void save(BizPurchase bizPurchase) {
		String purchaseId = "";
		//新增的时候添加信息
		if(null == bizPurchase.getPurchaseId() || bizPurchase.getPurchaseId().equals("")){
			purchaseId = IdGen.getUniqueKey();
			bizPurchase.setPurchaseId(purchaseId);
			String purchaseAutoCode = AutoNameUtils.createAutoNameByTableName("biz_purchase");
			bizPurchase.setPurchaseCode(purchaseAutoCode);
			bizPurchase.setPurchaseDate(new Date());
			bizPurchase.setStatus("1");
			bizPurchase.setAuditStatus("10");
			//添加操作日志
			bizPurchaseLogService.addBizPurchaseLog("新增",purchaseId);
			super.save(bizPurchase);

			//获取页面上的采购单明细
			List<BizPurchaseDetail> bizPurchaseDetailList = bizPurchase.getPurchaseDetailList();
			for (BizPurchaseDetail purchaseDetail:bizPurchaseDetailList) {
				//获取商品的信息
				BizGoods bizGoods = bizGoodsService.get(purchaseDetail.getGoodsId());
				//前台页面删除行的时候将采购单的delFlag 设置为1
				if(null != purchaseDetail.getDelFlag() && purchaseDetail.getDelFlag().equals("0")
						&& null != purchaseDetail.getExpertAmount() && !purchaseDetail.getExpertAmount().equals("")){
					//给商品修改采购数量（添加）
					Integer purchasingAmount = 0;
					if(null != bizGoods.getPurchasingAmount()){
						purchasingAmount = Integer.valueOf(bizGoods.getPurchasingAmount());
					}
					Integer num = purchasingAmount + Integer.valueOf(purchaseDetail.getExpertAmount());
					bizGoods.setPurchasingAmount(num.toString());
					bizGoodsService.updateInfo(bizGoods);

					//修改请购单明细的状态
					BizBuyingRequisitionDetail bizBuyingRequisitionDetail = bizBuyingRequisitionDetailDao.get(purchaseDetail.getBuyingDetailId());
					if(null != bizBuyingRequisitionDetail){
						Integer expertAmount = Integer.valueOf(purchaseDetail.getExpertAmount());	//当前采购量
						Integer outExpertAmount = bizBuyingRequisitionDetail.getOutExpertAmount();	//请购单明细已采购数增加当前采购数量
						Integer surplusExpertAmount = bizBuyingRequisitionDetail.getSurplusExpertAmount();	//请购单明细剩余可请购数减去当前采购量

						bizBuyingRequisitionDetail.setOutExpertAmount(expertAmount+outExpertAmount);
						bizBuyingRequisitionDetail.setSurplusExpertAmount(surplusExpertAmount-expertAmount);
						bizBuyingRequisitionDetailDao.update(bizBuyingRequisitionDetail);
					}

					//添加采购明细
					purchaseDetail.setPurchaseDetailId(IdGen.getUniqueKey());
					purchaseDetail.setPurchaseId(purchaseId);
					purchaseDetail.setActualAmount("0");
					purchaseDetail.setDifferentAmount(purchaseDetail.getExpertAmount());
					String unitPrice = purchaseDetail.getUnitPrice();
					if(StringUtils.isEmpty(unitPrice)){
						purchaseDetail.setUnitPrice("0.0");
					}
					User user = UserUtils.getUser();
					if(user != null && StringUtils.isNotEmpty(user.getId())){
						purchaseDetail.setCreateBy(user);
						purchaseDetail.setUpdateBy(user);
					}
					purchaseDetail.setCreateDate(new Date());
					purchaseDetail.setUpdateDate(new Date());
					bizPurchaseDetailDao.insert(purchaseDetail);
				}
			}
			//修改请购的状态
			BizBuyingRequisition bizBuyingRequisition = new BizBuyingRequisition();
			bizBuyingRequisition.setBuyingId(bizPurchase.getBuyingId());
			bizBuyingRequisition.setStatus("40");
			//查询是否全部采购
			Integer num = bizBuyingRequisitionDetailDao.selectCountByBuyingId(bizPurchase.getBuyingId());
			if(num == 0){
				bizBuyingRequisition.setStatus("50");
			}
			bizBuyingRequisitionDao.updateInfo(bizBuyingRequisition);
		}else{
			//添加操作日志
			bizPurchaseLogService.addBizPurchaseLog("修改",purchaseId);
			//修改对应请购单明细的剩余可请购数和已采购数
			List<BizPurchaseDetail> purchaseDetailList = bizPurchase.getPurchaseDetailList();
			for (BizPurchaseDetail purchaseDetail : purchaseDetailList) {

				if(null != purchaseDetail.getDelFlag() && purchaseDetail.getDelFlag().equals("0")
						&& StringUtils.isNotEmpty(purchaseDetail.getExpertAmount())){

					BizPurchaseDetail bizPurchaseDetail = bizPurchaseDetailService.get(purchaseDetail);	//数据库未修改采购单明细
					if(bizPurchaseDetail != null && StringUtils.isNotEmpty(bizPurchaseDetail.getExpertAmount())){
						//修改请购单明细的状态
						BizBuyingRequisitionDetail bizBuyingRequisitionDetail = bizBuyingRequisitionDetailDao.get(bizPurchaseDetail.getBuyingDetailId());
						if(null != bizBuyingRequisitionDetail){

							Integer expertAmount = Integer.valueOf(purchaseDetail.getExpertAmount());	//当前采购单明细数量
							Integer expertAmount2 = Integer.valueOf(bizPurchaseDetail.getExpertAmount());	//未修改采购单明细数量
							Integer actualAmount = Integer.valueOf(bizPurchaseDetail.getActualAmount());

							Integer outExpertAmount = bizBuyingRequisitionDetail.getOutExpertAmount();	//请购单明细已采购数减去历史采购数增加当前采购数量
							Integer surplusExpertAmount = bizBuyingRequisitionDetail.getSurplusExpertAmount();	//请购单明细剩余可请购数增加历采购数量减去当前采购量

							bizBuyingRequisitionDetail.setOutExpertAmount(outExpertAmount-expertAmount2+expertAmount);
							bizBuyingRequisitionDetail.setSurplusExpertAmount(surplusExpertAmount+expertAmount2-expertAmount);
							bizBuyingRequisitionDetailDao.update(bizBuyingRequisitionDetail);

							Integer differentAmount = expertAmount - actualAmount;
							purchaseDetail.setDifferentAmount(differentAmount + "");
						}
					}
				}
				bizPurchaseDetailDao.update(purchaseDetail);
			}
			super.save(bizPurchase);
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(BizPurchase bizPurchase) {
		super.delete(bizPurchase);
	}

	 /**
	  * 修改采购单
	  * @author tiancheng
	  * @date 2018/7/16 9:22
	  * @param
	  * @return
	  */
	@Transactional(readOnly = false)
	public void updateStatus(BizPurchase bizPurchase) {
		dao.updateStatus(bizPurchase);
	}

	/**
	 * 修改采购单审核状态
	 * @author xuchen
	 * @date 2018/12/03 16:44
	 * @param
	 * @return
	 */
	@Transactional(readOnly = false)
	public void updateAuditStatus(BizPurchase bizPurchase) {
		bizPurchaseDao.updateAuditStatus(bizPurchase);
	}

	/**
	 * 新增采购单
	 * @param bizPurchase
	 */
	@Transactional(readOnly = false)
	public void insert(BizPurchase bizPurchase) {
		bizPurchaseDao.insert(bizPurchase);
	}


	/**
	 * 更新采购单
	 * @param bizPurchase
	 */
	@Transactional(readOnly = false)
	public void update(BizPurchase bizPurchase) {
		bizPurchaseDao.update(bizPurchase);
	}
}